//
//  HETWViewController.m
//  HealthFamily
//
//  Created by 吴欧 on 2020/11/18.
//  Copyright © 2020 honglutec. All rights reserved.
//

#import "HETWViewController.h"
#import "HETWRaidoCell.h"
#import "HETWInputCell.h"
#import "HEOrderTitleCell.h"
#import "HEAddPhotoCell.h"
#import "HETWProtocalCell.h"
#import "HEUploadUtils.h"
#import "HEDoctorServerComfireViewController.h"
#import "HEDocOrderHeadCell.h"
#import "HETWSymptomCell.h"

@interface HETWViewController ()<UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) GDTableView *tableView;
@property (nonatomic, strong) GDFormModel *formModel;
@property (nonatomic, strong) NSMutableArray *sections;
@property (nonatomic, strong) NSMutableArray <HEDoctorCommentModel *> *commentList;
@property (nonatomic, strong) UIButton *bottomView;

// 创建一个全局的group
@property (nonatomic, strong) dispatch_group_t group;
@property (nonatomic, assign) CGFloat topHeight;
@property (nonatomic, strong) NSMutableArray *videoUrls;
@property (nonatomic, strong) GDFiterCellModel *zzModel;

@end

@implementation HETWViewController

- (GDFormModel *)formModel {
    if (!_formModel) {
        _formModel = [[GDFormModel alloc] init];
        _formModel.proxyVC = self;
    }
    return _formModel;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.title = @"图文咨询";
    
//    [self initNoticeTopView];

    [self initUI];
    [self initCell];
    [self initTabBarView];
    
    [self loadSymptomList];
}

- (void)initNoticeTopView {
    
    NSString *nstr = @"您可以长按右侧话筒图标，在震动之后即可对输入框进行语音输入~上传视频资料时，您可选择或录制2个不超过30秒的视频文件";
    _topHeight = [nstr heightForFont:DYFont(16) width:KScreenWidth-30] + 30;
    UIView *noticeWarp = [[UIView alloc] initWithFrame: CGRectMake(0, ZXNavBarHeight, KScreenWidth, _topHeight )];
    noticeWarp.backgroundColor = KHexColor(@"E8F2FE");
    [self.view addSubview:noticeWarp];
 
    UILabel *noticeLb = [UILabel new];
    noticeLb.text = nstr;
    noticeLb.textColor = CNavBgColor;
    noticeLb.numberOfLines = 0;
    noticeLb.font = DYFont(16);
    [noticeWarp addSubview:noticeLb];
    
    [noticeLb mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(noticeWarp).mas_offset(10);
        make.left.equalTo(noticeWarp).mas_offset(15);
        make.right.equalTo(noticeWarp).mas_offset(-15);
        make.bottom.equalTo(noticeWarp).mas_offset(-10);
    }];
}

- (void)initUI {
   _tableView = [[GDTableView alloc] initWithFrame:CGRectMake(0, ZXNavBarHeight, KScreenWidth, KScreenHeight- ZXNavBarHeight - ZXSafeAreaBottom - 49) style:UITableViewStyleGrouped];
    _tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, CGFLOAT_MIN)];
    _tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, CGFLOAT_MIN)];
    _tableView.showsVerticalScrollIndicator = NO;
    _tableView.showsHorizontalScrollIndicator = NO;
    
   _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
   _tableView.scrollsToTop = YES;
   _tableView.tableFooterView = [[UIView alloc] init];
   
   self.tableView.backgroundColor = KWhiteColor;
   self.tableView.delegate = self;
   self.tableView.dataSource = self;
   [self.view addSubview:self.tableView];
}

- (void)initCell {
   // 总段
   _sections = [NSMutableArray array];
   NSMutableArray *classArr = [NSMutableArray array];
    
    self.formModel.doc_details = _userModel;
    
    
    // 医生信息
    GDFiterCellModel *doctorModel = [GDFiterCellModel new];
    doctorModel.cellKlass = HEDocOrderHeadCell.class;

   // 症状
    GDFiterCellModel *zzModel = [GDFiterCellModel new];
    zzModel.cellKlass = HETWSymptomCell.class;
    zzModel.leftTitle = @"症状：";
    zzModel.placeHolder = @"请简单描述您的症状";
    zzModel.tableKey = @"tw_zx";
    zzModel.isHasMustSigns = YES;
    _zzModel = zzModel;
    
//
//    // 病情描述
//    GDFiterCellModel *bqModel = [GDFiterCellModel new];
//    bqModel.cellKlass = HETWInputCell.class;
//    bqModel.leftTitle = @"病情描述：";
//    bqModel.placeHolder = @"请详细描述您最近病情状况";
//    bqModel.tableKey = @"tw_bqms";
//    bqModel.isHasMustSigns = YES;
//
//
//    // 患病时长
//     GDFiterCellModel *hbTimeModel = [GDFiterCellModel new];
//    hbTimeModel.cellKlass = HETWInputCell.class;
//    hbTimeModel.leftTitle = @"患病时长：";
//    hbTimeModel.placeHolder = @"患病多久了（如1个月、半年）";
//    hbTimeModel.tableKey = @"tw_hbsc";
//    hbTimeModel.isHasMustSigns = YES;
//
//    // 希望获得的帮助
//    GDFiterCellModel *helpModel = [GDFiterCellModel new];
//    helpModel.cellKlass = HETWInputCell.class;
//    helpModel.leftTitle = @"希望获得的帮助：";
//    helpModel.placeHolder = @"请输入您希望医生为您提供的帮助";
//    helpModel.tableKey = @"tw_help";
//
//
//    // 用药情况
//     GDFiterCellModel *drugModel = [GDFiterCellModel new];
//    drugModel.cellKlass = HETWInputCell.class;
//    drugModel.leftTitle = @"用药情况：";
//    drugModel.placeHolder = @"请输入您最近或以往用药情况";
//    drugModel.tableKey = @"tw_drug";
//
//   // 过敏史
//    GDFiterCellModel *gmsModel = [GDFiterCellModel new];
//    gmsModel.cellKlass = HETWInputCell.class;
//    gmsModel.leftTitle = @"过敏史：";
//    gmsModel.placeHolder = @"请输入您的过敏史";
//    gmsModel.tableKey = @"tw_gms";
//
//    // 既往病史
//    GDFiterCellModel *jwsModel = [GDFiterCellModel new];
//    jwsModel.cellKlass = HETWInputCell.class;
//    jwsModel.leftTitle = @"既往病史：";
//    jwsModel.placeHolder = @"请输入您的历史患病情况";
//    jwsModel.tableKey = @"tw_jwbs";

    // 病例资料
    GDFiterCellModel *blTitleModel = [GDFiterCellModel new];
    blTitleModel.cellKlass = HEOrderTitleCell.class;
    blTitleModel.leftTitle = @"病例图片/视频资料";
    blTitleModel.cellType = GDFiterCellTypeDoctorOrderHead;
    
    // 上传照片
    GDFiterCellModel *photoModel = [GDFiterCellModel new];
    photoModel.cellKlass = HEAddPhotoCell.class;
    photoModel.cellType = GDFiterCellTypeSelect_ADDPHOTO;
    photoModel.cellHeight = 108;
    photoModel.lineNum = 4;
    photoModel.photoMangeType = GDCellPhotoManagerSelectedTypePhotoAndVideo;

    
    // 既往病史
    GDFiterCellModel *seeModel = [GDFiterCellModel new];
    seeModel.cellKlass = HETWRaidoCell.class;
    seeModel.leftTitle = @"是否就该疾病到医院就诊过";
    seeModel.tableKey = @"pd_jzJb";
    
    // 图文协议
    GDFiterCellModel *protocalModel = [GDFiterCellModel new];
    protocalModel.cellKlass = HETWProtocalCell.class;
    
   
   // 添加的时候注意顺序，暂未对顺序做处理
   classArr = @[doctorModel, zzModel, blTitleModel, photoModel, seeModel, protocalModel ].mutableCopy;
   [self.tableView mc_registerCellByFiterModels:classArr];
    
    for (GDFiterCellModel *model in classArr) {
         NSMutableArray *secs = [NSMutableArray array];
         
        // 隐藏未达到条件的cell
         if (model.cellDisplayType == GDCellDisplayNone) {
             continue;
         }
        
        if ([model.cellKlass isEqual: HETWInputCell.class]) {
            if ([model.leftTitle isEqual:@"病情描述"]) {
                model.cellHeight = 230;
            }else {
                model.cellHeight = 130;
            }
        }
        
        if (model.cellType == GDFiterCellTypeDoctorOrderHead) {
            continue;
        }
         else if (model.cellType == GDFiterCellTypeSelect_ADDPHOTO) {
             [secs addObject:blTitleModel];
             [secs addObject:model];
         }
         else if (model.cellType == GDFiterCellTypeOrderPay) {
           
         }
         else {
            [secs addObject:model];
        }
         
        [_sections addObject: secs];
     }
    
 
   [_tableView reloadData];
}

- (void)initTabBarView {
    UIButton *bottomView = [UIButton buttonWithType:UIButtonTypeCustom];
    _bottomView = bottomView;
    [self.view addSubview:bottomView];
    bottomView.backgroundColor = CNavBgColor;
    _bottomView.titleLabel.font = DYBlodFont(18);
    [bottomView setTitleColor:KWhiteColor forState:UIControlStateNormal];
    [bottomView addTarget:self action:@selector(submit) forControlEvents:UIControlEventTouchUpInside];
    
    [bottomView setTitle:@"立即咨询" forState:UIControlStateNormal];

    [bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(self.view);
        make.height.mas_offset(49);
        make.bottom.offset(-ZXSafeAreaBottom);
    }];
}

#pragma mark - load data
- (void)loadSymptomList {
    NSMutableDictionary *params = @{}.mutableCopy;
    [params setValue:@"oldman_disease" forKey:@"service"];
    [params setValue:@{} forKey:@"params"];

    [WOAFNetWorkingHandle POSTWithBaseUrl:KServerUrl suffixUrl:KReportData parameters:params success:^(id  _Nonnull responseObject) {
        DLog(@"%@", [responseObject mj_JSONString])
        HEResponse *response = [HEResponse mj_objectWithKeyValues:responseObject];
        
        // 常见症状
        NSArray *res = response.data[@"result"];
        
        NSMutableArray *items = @[].mutableCopy;
        for (NSDictionary *dict in res) {
            [items addObject:dict[@"item_value"]];
        }
        NSArray *times = @[@"1~2天", @"3~5天", @"一周", @"半个月", @"一个月", @"一个月以上"];
        NSArray *section = @[items, times];
        self.zzModel.cellData = section;
        [self.tableView reloadData];
    } failure:^(NSError * _Nonnull error) {
        
    }];
}

#pragma mark -
- (void)submit {

    if ([DYTools isBlankString:self.formModel.tw_zx]) {
        [Dialog toastBottom:@"请简单描述您的症状"];
        return;
    }

//    if ([DYTools isBlankString:self.formModel.tw_bqms]) {
//        [Dialog toastBottom:@"请详细描述您最近病情状况"];
//        return;
//    }

//    if ([DYTools isBlankString:self.formModel.tw_hbsc]) {
//        [Dialog toastBottom:@"患病多久了（如1个月、半年）"];
//        return;
//    }
 
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_async(queue, ^{
        self.group = dispatch_group_create();
        
        [self uploadVideo: self.formModel];
        // 上传图片
        [self uploadImage: self.formModel];
        
        //因上面请求中有加入dispatch_group_enter 和 dispatch_group_leave,所以真正等待上面线程执行完才执行这里面的请求
        dispatch_group_notify(self.group, queue, ^{
            [self createSubmitRequest];
        });
    });
}

- (void)createSubmitRequest {
    NSMutableDictionary *params = @{}.mutableCopy;
    [params setValue: [NSNumber numberWithBool:self.formModel.tw_hasSee] forKey:@"is_visit"];
    [params setValue: @1 forKey:@"ask_level"];
    [params setValue: _formModel.tw_zx forKey:@"ask_type"];
    [params setValue: _userModel.user_id forKey:@"doc_id"];
    [params setValue: @4 forKey:@"status"];
    
    NSArray *askArrs = @[
        @{@"title":@"症状：", @"content":IsNotNull(_formModel.tw_zx), @"type":@"text"},
//        @{@"title":@"病情描述：", @"content":IsNotNull(_formModel.tw_bqms), @"type":@"text"},
//        @{@"title":@"患病时长：", @"content":IsNotNull(_formModel.tw_hbsc), @"type":@"text"},
//        @{@"title":@"希望获得的帮助：", @"content":IsNotNull(_formModel.tw_help), @"type":@"text"},
//        @{@"title":@"用药情况：", @"content":IsNotNull(_formModel.tw_drug), @"type":@"text"},
//        @{@"title":@"过敏史：", @"content":IsNotNull(_formModel.tw_gms), @"type":@"text"},
//        @{@"title":@"既往病史：", @"content":IsNotNull(_formModel.tw_jwbs), @"type":@"text"},
        @{@"title":@"病例图片资料：", @"content":IsNotNull([_formModel.cm_imgUrls componentsJoinedByString:@","]), @"type":@"image"},
        @{@"title":@"病例视频资料：", @"content": IsNotNull([_videoUrls componentsJoinedByString:@","]), @"type":@"video"}
    ];
    [params setValue:[askArrs mj_JSONString] forKey:@"user_ask"];
    
    [WOAFNetWorkingHandle POSTWithBaseUrl:KServerUrl suffixUrl:KuserAsk parameters:params success:^(id  _Nonnull responseObject) {
        NSLog(@"response：  %@", [responseObject mj_JSONString]);

        HEResponse *response = [HEResponse mj_objectWithKeyValues:responseObject];
        HEDoctorInfoModel *form = [HEDoctorInfoModel mj_objectWithKeyValues:response.data];
        if (response.success) {
            HEDoctorServerComfireViewController *vc = [HEDoctorServerComfireViewController new];
            
            HEServerComfireModel *comfireModel = [HEServerComfireModel new];
            comfireModel.icon_url = self.userModel.avatar;
            comfireModel.topStr = self.userModel.realname;
            comfireModel.middleStr = self.userModel.KDeptStr;
            comfireModel.bottomStr = self.userModel.hospital_name;
            comfireModel.payParams = @[self.selectServerModel.server_name,
                                       [NSString stringWithFormat:@"￥%@%@", [NSDecimalNumber rounding:self.selectServerModel.price afterPoint:2], self.selectServerModel.unit]];
            
            HECreateOrderRequest *request = [HECreateOrderRequest new];
            request.orderType = HEOrderTypeGeneral;
            request.doctor_id = self.userModel.user_id;
            request.total = 1;
            request.goodsId = self.selectServerModel.goods_id;
            request.channel = self.selectServerModel.channel;
            request.skuId = self.selectServerModel.attr_id;
            request.source = HEOrderSourceTypeiOS;
            request.type = HESubmitPreviewTypeByGoodsDetails;
            request.appSource = KAppSource;
            
            HEExtraDoctorInfoModel *extra = [HEExtraDoctorInfoModel new];
            extra.planId = -1;
            extra.order_type = self.selectServerModel.channel;
            extra.inst_id = form.inst_id;

            extra.doctor_info = [DoctorInfo new];
            extra.doctor_info.user_id = self.userModel.user_id;
            extra.doctor_info.post_name = self.userModel.post_name;
            extra.doctor_info.avatar = self.userModel.avatar;
            extra.doctor_info.depart_name = self.userModel.depart_name;
            extra.doctor_info.realname = self.userModel.realname;
            request.extras = [extra mj_JSONString];
            
            vc.comfireModel = comfireModel;
            vc.orderRequest = request;
            vc.price = self.selectServerModel.price;
            [self.navigationController pushViewController:vc animated:YES];
        }
    } failure:^(NSError * _Nonnull error) {

    }];
}

- (void)uploadVideo:(GDFormModel *)model {
    dispatch_group_enter(_group);
    _videoUrls = @[].mutableCopy;

    if (!(model.cm_video.count > 0)) {
        dispatch_group_leave(self.group);
        return;
    }
    
    HEUploadUtils *upload = [HEUploadUtils new];
    [upload uploadVideos:model.cm_video progress:^(int64_t bytesProgress, int64_t totalBytesProgress) {
            
    } success:^(id  _Nonnull responseObject) {
        HEUploadResponse *response = [HEUploadResponse mj_objectWithKeyValues:responseObject];
        NSArray *array = [response.data.src componentsSeparatedByString:@","];
        for (NSString *url in array) {
            if (![DYTools isBlankString:url]) {
                [_videoUrls addObject:url];
            }
        }
        dispatch_group_leave(self.group);
    } failure:^(NSError * _Nonnull error) {
        dispatch_group_leave(self.group);
    }];
}


- (void)uploadImage:(GDFormModel *)model {
    dispatch_group_enter(_group);
    model.cm_imgUrls = @[].mutableCopy;

    if (!(model.cm_imgs.count > 0)) {
        dispatch_group_leave(self.group);
        return;
    }
    
    [WOAFNetWorkingHandle uploadImagesWithBaseURL:KServerUrl suffixUrl:Kbatch parameters:@{} name:nil images:model.cm_imgs fileNames:nil imageScale:0.8 imageType:nil progress:^(int64_t bytesProgress, int64_t totalBytesProgress) {
        

    } success:^(id  _Nonnull responseObject) {
        
        HEUploadResponse *response = [HEUploadResponse mj_objectWithKeyValues:responseObject];

        NSArray *array = [response.data.src componentsSeparatedByString:@","];
        for (NSString *url in array) {
            if (![DYTools isBlankString:url]) {
                [model.cm_imgUrls addObject:url];
            }
        }
        dispatch_group_leave(self.group);

    } failure:^(NSError * _Nonnull error) {
        dispatch_group_leave(self.group);
    }];
}

  

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
   return _sections.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
   NSMutableArray *sec = _sections[section];
   return sec.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSMutableArray *sec = _sections[indexPath.section];
    GDFiterCellModel *fiterModel = sec[indexPath.row];

    MCTableBaseCell *cell = (MCTableBaseCell *)[_tableView mc_dequeueReusableCellWithClassType:fiterModel.cellKlass];
    cell.proxyVC = self;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    fiterModel.fiterCellModelBlock((MCTableBaseCell *)cell, fiterModel, self.formModel, indexPath);
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
  NSMutableArray *sec = _sections[indexPath.section];
   GDFiterCellModel *fiterModel = sec[indexPath.row];

    if ([fiterModel.cellKlass isEqual: HETWInputCell.class] ||
        fiterModel.cellType == GDFiterCellTypeSelect_ADDPHOTO) {
        return fiterModel.cellHeight;
    }
   return [tableView fd_heightForCellWithIdentifier: NSStringFromClass(fiterModel.cellKlass) cacheByIndexPath:indexPath configuration:^(MCTableBaseCell *cell) {
              [cell refreshContent:fiterModel formModel:self.formModel indexPath:indexPath];
   }];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
   NSMutableArray *sec = _sections[indexPath.section];
    GDFiterCellModel *fiterModel = sec[indexPath.row];
 
}

#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return CGFLOAT_MIN;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    NSMutableArray *sec = _sections[section];
    GDFiterCellModel *fiterModel = sec.lastObject;
    
    if (section == 0) {
        return CGFLOAT_MIN;
    }
    return 10;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *v = [[UIView alloc] init];
    v.backgroundColor = CViewBgColor;
    return v;
}
 

#pragma mark - UITableViewDelegate
  
- (void)changeTabbarView {
 
}



@end
